<template>
  <div class="device-account-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main class="container">
      <div class="search-container">
        <div class="search-item">
          <div class="label">关键字：</div>
          <div class="content">
            <el-input
              v-model="condition"
              placeholder="根据计划名称筛选"
              @blur="handleSearch"
              @keydown.native.enter="handleSearch"></el-input>
          </div>
          <div class="label">审核状态：</div>
          <div class="content">
            <el-select placeholder="请选择审核状态" v-model="status" @change="handleSearch">
              <el-option label="待提交" value="1"></el-option>
              <el-option label="审核中" value="2"></el-option>
              <el-option label="待审核" value="3"></el-option>
              <el-option label="已通过" value="4"></el-option>
              <el-option label="已驳回" value="5"></el-option>
            </el-select>
          </div>
          <el-button class="search-btn" type="primary" @click="handleSearch">
            <i class="el-icon-search"></i>
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <i class="el-icon-refresh"></i>
          </el-button>
        </div>
        <div class="search-item">
          <el-button v-if="hasTabAdd" type="primary" @click="handleAdd">新增</el-button>
        </div>
      </div>
      <el-table
        class="table-container"
        :data="tableData"
        v-loading="tableLoading"
        element-loading-custom-class="custom-load"
        row-key="id">
        <el-table-column label="序号" type="index" width="120"></el-table-column>
        <el-table-column label="计划名称" prop="planName"></el-table-column>
        <el-table-column label="创建人" prop="createName"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            {{ statusOptions[scope.row.reviewStatus] || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="审核人" prop="reviewName"></el-table-column>
        <el-table-column label="上传时间" prop="modifyTime"></el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <span style="display: none">{{scope.row.hasCheck}}</span>
            <span
              v-if="hasTableCheck && scope.row.hasCheck"
              class="btn"
              @click="handleEdit(scope.row, 'check')">审核</span>
            <span
              v-if="hasTableEdit && scope.row.hasEdit"
              class="btn"
              @click="handleEdit(scope.row, 'edit')">编辑</span>
            <span
              v-if="hasTableDel && scope.row.hasDelete"
              class="btn"
              @click="handleDelete(scope.row)">删除</span>
            <span
              v-if="hasTableDetail"
              class="btn"
              @click="handleEdit(scope.row, 'detail')">查看</span>
          </template>
        </el-table-column>
        <div class="empty-content" slot="empty">
          <i class="iconfont iconwushuju"></i>
          <p>暂无数据</p>
        </div>
      </el-table>
      <el-pagination
        v-if="total > 10"
        :page-size="pageSize"
        :current-page="pageNo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <add-plan
        :visible="visible"
        :type="type"
        :id="planId"
        :options="currentData"
        @cancel="visible = false"
        @submit="handleSave">
      </add-plan>
    </main>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import addPlan from '@/components/project/device/addPlan';

export default {
  data() {
    return {
      breadcrumbData: [
        { name: '机械设备' },
        { name: '设备计划' }
      ],
      // 列表数据
      tableData: [],
      tableLoading: false,
      total: 0,
      pageSize: 10,
      pageNo: 1,
      condition: '',
      statusOptions: {
        '1': '暂存',
        '2': '审核中',
        '3': '回退',
        '4': '审核完成'
      },
      visible: false,
      type: 'add',
      planId: '',
      hasSearch: false,
      status: '',
      currentData: {}
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userInfo() {
      return this.$store.state.userInfo;
    }
  },
  watch: {
    visible(val) {
      if (!val) {
        this.planId = '';
        this.currentData = {};
      }
    }
  },
  async created() {
    this.getTableData();
  },
  components: {
    addPlan,
    Breadcrumb
  },
  methods: {
    /**
     * 获取列表数据
     */
    async getTableData() {
      this.tableLoading = true;
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        projectId: this.projectId,
        ...this.setParams()
      };
      if (this.hasSearch) {
        params.condition = this.condition;
      }
      const { success, data: { data }} = await this.$Model.getMachPlanList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        const { uuid } = this.userInfo;
        this.tableData = list.map(item => {
          // reviewStatus 审核状态：（1：暂存；2：审核中；3：回退；4：审核完成）
          const { reviewStatus, reviewUser, createUser } = item;
          return {
            ...item,
            hasCheck: uuid === reviewUser && reviewStatus === '2',
            hasEdit: uuid === createUser && ['1', '2'].includes(reviewStatus),
            hasDelete: uuid === createUser
          };
        });
        this.total = data.total || 0;
      }
    },
    setParams() {
      const result = {};
      if (!this.status) return result;
      const { uuid } = this.userInfo;
      switch (this.status) {
        case '1':
          result.createUser = uuid;
          result.reviewStatus = '1';
          break;
        case '2':
          result.createUser = uuid;
          result.reviewStatus = '2';
          break;
        case '3':
          result.reviewUser = uuid;
          result.reviewStatus = '2';
          break;
        case '4':
          result.reviewStatus = '4';
          break;
        case '5':
          result.reviewStatus = '3';
          break;
        default: break;
      }
      return result;
    },
    handleSearch() {
      this.clear();
      this.getTableData();
    },
    handleRefresh() {
      this.condition = '';
      this.status = '';
      this.clear();
      this.getTableData();
    },
    handleAdd() {
      this.type = 'add';
      this.planId = '';
      this.currentData = {};
      this.visible = true;
    },
    // 查看
    handleEdit(row, type) {
      this.type = type;
      this.planId = row.id;
      this.currentData = { ... row };
      this.visible = true;
    },
    /**
     * 删除计划
     * @param row {Object}
     */
    handleDelete(row) {
      this.$confirm('此操作将删除该计划, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.deleteDevicePlan({
          id: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.clear();
          this.getTableData();
        }
      });
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getTableData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getTableData();
    },
    async handleSave(data) {
      const params = {
        ...data
      };
      const { success } = await this.$Model.planSave(params);
      if (success) {
        this.$message.success('保存成功');
        this.getTableData();
        this.visible = false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .device-account-page {
    width: 100%;
    height: 100%;
    background-color: $mainBg;
    overflow: hidden;
    main {
      width: 100%;
      height: calc(100% - 50px);
      padding: 20px;
      .search-container {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
        .search-item {
          display: flex;
          align-items: center;
          .el-input {
            width: 300px;
            margin-right: 20px;
          }
        }
        .search-btn {
          margin-left: 20px;
        }
      }
      .table-container {
        height: calc(100% - 120px);
        /deep/ .el-table__body-wrapper {
          height: calc(100% - 50px);
          padding-bottom: 46px;
          overflow-y: auto;
          .btn {
            padding: 0 5px;
            cursor: pointer;
            color: $mainColor;
          }
        }
        /deep/ .el-table__header {
          th.is-leaf .el-button span {
            color: #fff;
          }
        }
      }

    }
  }
</style>
